package fr.dauphine.bookstore.backoffice.author;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;

import fr.dauphine.bookstore.backoffice.SessionUtil;
import fr.dauphine.bookstore.commun.MessagesUtil;
import fr.dauphine.bookstore.hibernate.HibernateUtil;
import fr.dauphine.bookstore.modele.Author;

/**
 * Ajout et modification d'un auteur.
 */
public final class SaveAuthorServlet extends HttpServlet {

	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = 5347836201142869831L;

	/**
	 * Traite la methode POST.
	 * 
	 * @param request
	 *            Requete
	 * @param response
	 *            Reponse
	 * @throws ServletException
	 *             Erreur de servlet
	 * @throws IOException
	 *             Erreur d'entree/sortie
	 */
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		Author author = SessionUtil.getAuthor(request.getSession());

		// Last name
		author.setLastName(request.getParameter("lastName"));

		if (StringUtils.isEmpty(author.getLastName())) {
			MessagesUtil.addMessage(request, MessagesUtil.ERROR, "Le nom est obligatoire");
		}

		// First name
		author.setFirstName(request.getParameter("firstName"));

		if (StringUtils.isEmpty(author.getFirstName())) {
			MessagesUtil.addMessage(request, MessagesUtil.ERROR, "Le prenom est obligatoire");
		}

		// On sauvegarde
		if (!MessagesUtil.isThereErrors(request)) {

			Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
			hSession.saveOrUpdate(author);
			SessionUtil.removeAuthor(request.getSession());

			response.sendRedirect("authors.jsp");

			// On retourne sur la page de modification
		} else {
			request.getRequestDispatcher("editAuthor.jsp").forward(request, response);
		}
	}
}
